﻿using System;
using System.IO;
using HttpService.Collect;
using RpcHelper;
using RpcHelper.Config;

namespace HttpService.Config
{
    public class GzipConfig
    {
        /// <summary>
        /// 是否启用压缩
        /// </summary>
        public bool IsEnable
        {
            get;
            set;
        } = true;
        /// <summary>
        /// 需要压缩的文件扩展名
        /// </summary>
        public string[] Extensions
        {
            get;
            set;
        } = new string[] { ".txt", ".html", ".css", ".js", ".htm", ".xml", ".json", ".docx", ".doc", ".xlsx", ".xls" };
        /// <summary>
        /// 最小文件大小
        /// </summary>
        public int MinFileSzie
        {
            get;
            set;
        } = 1024 * 10;
        /// <summary>
        /// 是否缓存为文件
        /// </summary>
        public bool IsCacheFile
        {
            get;
            set;
        } = true;
        /// <summary>
        /// 缓存目录
        /// </summary>
        public string CacheDir
        {
            get;
            set;
        } = "ZipCache";
        /// <summary>
        /// 是否压缩API接口返回的文本
        /// </summary>
        public bool IsZipApiText
        {
            get;
            set;
        } = true;
        /// <summary>
        /// API接口返回的文本限定长度
        /// </summary>
        public int TextLength
        {
            get;
            set;
        } = 1000;
        private bool _IsInit = false;
        internal void Init()
        {
            if (!this._IsInit)
            {
                this._IsInit = true;
                LocalConfig.Local.RefreshEvent += this.Local_RefreshEvent;
            }
            if (this.IsEnable)
            {
                if (this.CacheDir.IsNull())
                {
                    this.CacheDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ZipCache");
                }
                else if (!Path.IsPathRooted(this.CacheDir))
                {
                    this.CacheDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, this.CacheDir);
                }
                if (this.CacheDir.EndsWith('\\'))
                {
                    this.CacheDir = this.CacheDir.Remove(this.CacheDir.Length - 1, 1);
                }
                GzipCollect.Enable(this);
            }
            else
            {
                GzipCollect.Stop(this);
            }
        }

        private void Local_RefreshEvent(IConfigCollect config, string name)
        {
            if (name.StartsWith("http:gzip:") || name == "http:gzip")
            {
                GzipConfig gzip = config.GetValue<GzipConfig>("http:gzip");
                if (this.SetObjectValue(gzip) > 0)
                {
                    this.Init();
                }
            }
        }
    }
}
